package com.ta.stage.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ta.stage.entity.User;
import com.ta.stage.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.debug("登录成功之后开始授权");
        System.out.println("执行了授权.............................................");
        // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        //设置安全管理器
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给用户授予权限:拿到当前登录用户
        //info.addStringPermission("user:add");
        Subject subject = SecurityUtils.getSubject();
        //shiro从当前获取用户信息
        User user = (User) subject.getPrincipal();//拿到user对象


        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的输入的账号.
        System.out.println("认证..................................");
        //用户名和密码
        //String username = "root";
        //String password = "123456";
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //连接真实的数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //queryWrapper.and("username",userToken.getUsername());
        queryWrapper.like("username",userToken.getUsername());
        User user = userService.getOne(queryWrapper);

        if (user==null){//没有这个人
            return null;
        }

        if(!userToken.getUsername(). equals(user.getUsername())){
            return null;
        }
        //密码认证
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }


}
